import axios, { AxiosInstance, InternalAxiosRequestConfig } from 'axios';
  const isProduction = process.env.NEXT_PUBLIC_ENV === "production";
  
  // 创建 Axios 实例，baseURL 统一为 /api，交由 next.config.ts 代理转发
  const apiClient: AxiosInstance = axios.create({
    baseURL: isProduction
      ? process.env.NEXT_PUBLIC_API_BASE_URL + "/wxpubpay"
      : "/api",
    timeout: 10000,
    headers: {
      "Content-Type": "application/json",
      NOAES: 1,
    },
    withCredentials: !isProduction,
  });
  
  // 添加请求拦截器
  apiClient.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
      // 移除 CORS 相关 header，交由 next 代理处理
      if (typeof window !== 'undefined') {
        const token = localStorage.getItem('token');
        if (token) {
          config.headers.set('Authorization', `Bearer ${token}`);
        }
      }
      return config;
    },
    (error) => {
      return Promise.reject(error);
    }
  );
  
  // 添加响应拦截器
  apiClient.interceptors.response.use(
    (response) => response.data,
    (error) => {
      if (error.response && error.response.status === 401) {
        console.error('Unauthorized access, redirecting to login...');
        if (typeof window !== 'undefined') {
          window.location.href = '/login';
        }
      }
      return Promise.reject(error);
    }
  );
  
  export default apiClient;